﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tunynet;
using Tunynet.Caching;
using Tunynet.Repositories;

namespace Spacebuilder.Common
{
    /// <summary>
    /// 理想对象
    /// </summary>
   public  class EachRequestRepository : Repository<EachRequest>, IEachRequestRepository
    {

        /// <summary>
        /// 通过用户ID查找
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
       public EachRequest EachCaseOfUser(long userId)
        {
            StringBuilder cacheKey = new StringBuilder(RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "userId", userId));
            cacheKey.AppendFormat("EachCaseOfUser");
            IEnumerable<EachRequest> BaseCaseIds = cacheService.Get<IEnumerable<EachRequest>>(cacheKey.ToString());
            if (BaseCaseIds == null || BaseCaseIds.Count() == 0)
            {
                var sql = PetaPoco.Sql.Builder;
                sql.Select("*")
                .From("spb_EachRequests")
                .Where("UserId = @0", userId);
                BaseCaseIds = CreateDAO().Fetch<EachRequest>(sql);
                cacheService.Set(cacheKey.ToString(), BaseCaseIds, CachingExpirationType.UsualObjectCollection);
            }
            return BaseCaseIds.FirstOrDefault();
        }

        /// <summary>
        /// 获取所有理想对象基本信息
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
       public IEnumerable<long> GetEachRequestOfUser(long userId)
        {
            StringBuilder cacheKey = new StringBuilder(RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "userId", userId));
            cacheKey.AppendFormat("GetEachRequestOfUser");
            IEnumerable<long> EachRequestIds = cacheService.Get<IEnumerable<long>>(cacheKey.ToString());
            if (EachRequestIds == null || EachRequestIds.Count() == 0)
            {
                var sql = PetaPoco.Sql.Builder;
                sql.Select("id")
                .From("spb_EachRequests")
                .Where("UserId = @0", userId);
                EachRequestIds = CreateDAO().FetchFirstColumn(sql).Cast<long>();
                cacheService.Set(cacheKey.ToString(), EachRequestIds, CachingExpirationType.UsualObjectCollection);
            }
            return EachRequestIds;
        }

        /// <summary>
        /// 根据用户ID列表获取理想对象ID列表，本方法现用于用户搜索功能的索引生成
        /// </summary>
        /// <param name="userIds">用户ID列表</param>
        /// <returns>工作经历ID列表</returns>
        public IEnumerable<long> GetEntityIdsByUserIds(IEnumerable<long> userIds)
        {
            var sql = PetaPoco.Sql.Builder;
            sql.Select("Id")
                   .From("spb_EachRequests")
                   .Where("UserId in (@userIds)", new { userIds = userIds });
            return CreateDAO().Fetch<long>(sql);
        }
    }
}
